from typing import List

class Solution:
    def candy(self, ratings: List[int]) -> int:
        n = len(ratings)
        # 初始化糖果数组，每个孩子至少1个糖果
        candies = [1] * n
        
        # 从左向右遍历，确保右边评分高的孩子获得更多糖果
        for i in range(1, n):
            if ratings[i] > ratings[i-1]:
                candies[i] = candies[i-1] + 1
        
        # 从右向左遍历，确保左边评分高的孩子获得更多糖果
        for i in range(n-2, -1, -1):
            if ratings[i] > ratings[i+1]:
                candies[i] = max(candies[i], candies[i+1] + 1)
        
        # 返回总糖果数
        return sum(candies)

# 测试代码
if __name__ == "__main__":
    solution = Solution()
    
    # 测试用例1
    ratings1 = [1, 0, 2]
    print(f"测试用例1: {ratings1}")
    print(f"最少糖果数: {solution.candy(ratings1)}")  # 预期输出: 5
    
    # 测试用例2
    ratings2 = [1, 2, 2]
    print(f"\n测试用例2: {ratings2}")
    print(f"最少糖果数: {solution.candy(ratings2)}")  # 预期输出: 4 